#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "MQTTClient.h"
#include <pthread.h>
#include "mqtt.h"
#define ADDRESS "tcp://192.168.10.34:1883" //根据 MQTT 实际主机地址调整
#define CLIENTID_PUB "ExampleClientPub"
#define CLIENTID_SUB "ExampleClientSub"
#define QOS 1
#define TIMEOUT 10000L
//#define PUB_TOPIC "ScratchToSoftWare" //可根据虚拟仿真软件网关的设置对应调整
#define MQTT_SUB_TOPIC "SoftWareToScratch" //可根据虚拟仿真软件网关的设置对应调整
#define NUM_THREADS 2
#define FAN_OFF "{'fan':false}"
#define FAN_ON "{'fan':true}"

//#define LIGHT   "{\"light\":%f, \"id\":\"%d\"}"
//#define TEMP   "{\"tem\":%f, \"hum\":%f,\"id\":\"%d\"}"
//#define LAMP    "{\"lamp\":%s, \"id\":\"%d\"}"
//#define SUNSHADE_FORDWARD "{'sunshade':forward}"
//#define SUNSHADE_REVERSE "{'sunshade':reverse}"
//#define SUNSHADE_STOP "{'sunshade':stop}"
//#define PUB_TOPIC   "FS_FARM/gate/1002"

MQTTClient client;
int fan_state = 0;
volatile MQTTClient_deliveryToken deliveredtoken;


pthread_mutex_t mqtt_msg_mutex;
pthread_cond_t mqtt_msg_cond;

void delivered(void *context, MQTTClient_deliveryToken dt)
{
    printf("Message with token value %d delivery confirmed\n", dt);
    deliveredtoken = dt;
}
int msgarrvd(void *context, char *topicName, int topicLen, MQTTClient_message *message)
{

    printf("Message arrived\n");
    printf(" topic: %s\n", topicName);
    printf(" message: %.*s\n", message->payloadlen, (char *)message->payload);
    MQTTClient_freeMessage(&message);
    MQTTClient_free(topicName);
    return 1;
}
void connlost(void *context, char *cause)
{
    printf("\nConnection lost\n");
    printf(" cause: %s\n", cause);
}
void *mqtt_subscribe()
{
    MQTTClient client;
    MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
    int rc;
    if ((rc = MQTTClient_create(&client, ADDRESS, CLIENTID_SUB,
                                MQTTCLIENT_PERSISTENCE_NONE, NULL)) != MQTTCLIENT_SUCCESS)
    {
        printf("Failed to create client, return code %d\n", rc);
        rc = EXIT_FAILURE;
        goto exit;
    }
    if ((rc = MQTTClient_setCallbacks(client, NULL, connlost, msgarrvd,
                                      delivered)) != MQTTCLIENT_SUCCESS)
    {
        printf("Failed to set callbacks, return code %d\n", rc);
        rc = EXIT_FAILURE;
        goto destroy_exit;
    }
    conn_opts.keepAliveInterval = 20;
    conn_opts.cleansession = 1;
    if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
    {
        printf("Failed to connect, return code %d\n", rc);
        rc = EXIT_FAILURE;
        goto destroy_exit;
    }

    printf("Subscribing to topic %s\nfor client %s using QoS%d\n\n"
           "Press Q<Enter> to quit\n\n",
           MQTT_SUB_TOPIC, CLIENTID_SUB, QOS);
    if ((rc = MQTTClient_subscribe(client, MQTT_SUB_TOPIC, QOS)) != MQTTCLIENT_SUCCESS)
    {
        printf("Failed to subscribe, return code %d\n", rc);
        rc = EXIT_FAILURE;
    }
    else
    {
        int ch;
        do
        {
            ch = getchar();
        } while (ch != 'Q' && ch != 'q');
        if ((rc = MQTTClient_unsubscribe(client, MQTT_SUB_TOPIC)) != MQTTCLIENT_SUCCESS)
        {
            printf("Failed to unsubscribe, return code %d\n", rc);
            rc = EXIT_FAILURE;
        }
    }
    if ((rc = MQTTClient_disconnect(client, 10000)) != MQTTCLIENT_SUCCESS)
    {
        printf("Failed to disconnect, return code %d\n", rc);
        rc = EXIT_FAILURE;
    }
destroy_exit:
    MQTTClient_destroy(&client);
exit:
    return NULL;
}
void *mqtt_publish(char * topic, char * data)
{

    int rc;
    MQTTClient_message pubmsg = MQTTClient_message_initializer;
    MQTTClient_deliveryToken token;
    pubmsg.qos = QOS;
    pubmsg.retained = 0;
    pubmsg.payload = data;
    pubmsg.payloadlen = strlen(data);
    printf("data:%s\n", data);
    if ((rc = MQTTClient_publishMessage(client, topic,
                                        &pubmsg, &token)) != MQTTCLIENT_SUCCESS)
    {
        printf("Failed to publish message[%s], return code %d\n", data, rc);
        exit(EXIT_FAILURE);
    }

    // printf("Waiting for up to %d seconds for publication of %s\n"
    //        "on topic %s for client with ClientID: %s\n",
    //        (int)(TIMEOUT / 1000), data, PUB_TOPIC, CLIENTID_PUB);
    rc = MQTTClient_waitForCompletion(client, token, TIMEOUT);


    return NULL;
}


void exit_mqtt()
{
    int rc;
    if ((rc = MQTTClient_disconnect(client, 10000)) != MQTTCLIENT_SUCCESS)
        printf("Failed to disconnect, return code %d\n", rc);

    MQTTClient_destroy(&client);
}

int init_mqtt()
{
    // pthread_t threads[NUM_THREADS];
    //pthread_create(&threads[0], 0, mqtt_subscribe, NULL);
    pthread_mutex_init(&mqtt_msg_mutex,NULL);
    pthread_cond_init(&mqtt_msg_cond, NULL);
    char uri[128] = {0};
    
    //   GetProfileString(DEF_CONF_FILE, "mqtt", "uri", uri);
    int rc;
    MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
    if ((rc = MQTTClient_create(&client, ADDRESS, CLIENTID_PUB,

                                MQTTCLIENT_PERSISTENCE_NONE, NULL)) != MQTTCLIENT_SUCCESS)
    {
        printf("Failed to create client, return code %d\n", rc);
        exit(EXIT_FAILURE);
    }
    conn_opts.keepAliveInterval = 20;
    conn_opts.cleansession = 1;
    if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
    {
        printf("Failed to connect, return code %d\n", rc);
        exit(EXIT_FAILURE);
    }
    
    return 0;
}
